package org.sgx.gapi.client.apis.drive.file;

import org.sgx.gapi.client.GAPI;
import org.sgx.gapi.client.client.ClientRequest;
import org.sgx.gapi.client.client.ClientRequestCallback;
import org.sgx.gapi.client.client.GAPICallback;
import org.sgx.gapi.client.client.GAPIRequest;
import org.sgx.gapi.client.client.GAPIResult;
import org.sgx.gapi.client.client.HttpRequest;
import org.sgx.jsutil.client.JsObject;

import com.google.gwt.core.client.JsonUtils;
import com.google.gwt.json.client.JSONObject;
/**
 * Drive File Insert operation. See https://developers.google.com/drive/v2/reference/files/insert
 * File content transmited in a base64 string as in the example.
 * @author sg
 *
 */
public class DriveFileInsertRequest implements GAPIRequest<File> {

	String title, mimeType, base64Data;
	
	public DriveFileInsertRequest(String title, String mimeType, String base64Data) {
		super();
		this.title = title;
		this.mimeType = mimeType;
		this.base64Data = base64Data;
	}

	@Override
	public void execute(final GAPICallback<File> c) {

		//build the body: 
		
		String boundary = "-------314159265358979323846";
		String delimiter = "\r\n--" + boundary + "\r\n";
		String close_delim = "\r\n--" + boundary + "--";
		
		JsObject metaData = JsObject.createObject().cast();
		metaData.objPut("title", title);
		metaData.objPut("mimeType", mimeType);
		
		String multipartRequestBody =
	        delimiter +
	        "Content-Type: application/json\r\n\r\n" +
    		new JSONObject(metaData).toString() +
	        delimiter +
	        "Content-Type: " + mimeType + "\r\n" +
	        "Content-Transfer-Encoding: base64\r\n" +
	        "\r\n" +
	        base64Data +
	        close_delim;
				
		JsObject params = JsObject.createObject().cast();
		params.objPut("uploadType", "multipart").objPut("title", title); 
		
		JsObject headers = JsObject.createObject().cast();
		headers.objPut("Content-Type", "multipart/mixed; boundary=\""+boundary+"\""); 
		
		ClientRequest clientReq = ClientRequest.create()
				.path("/upload/drive/v2/files")
				.params(params)
				.method("post")
				.body(multipartRequestBody)
				.headers(headers);
		HttpRequest req = GAPI.get().client().request(clientReq);
		req.execute(new ClientRequestCallback() {
			@Override
			public void call(GAPIResult jsonResp, String rawResp) {
				c.call((File) jsonResp);
			}
		});
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getMimeType() {
		return mimeType;
	}

	public void setMimeType(String mimeType) {
		this.mimeType = mimeType;
	}

	public String getBase64Data() {
		return base64Data;
	}

	public void setBase64Data(String base64Data) {
		this.base64Data = base64Data;
	}

}
